<template>
  <el-dialog :visible="isShowDialog" :title="cateData.id?'编辑分类':'新增分类'" @close="btnCancel">
    <el-form ref="addInfo" label-width="80px" :model="formData" :rules="rules">
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="formData.desc" />
      </el-form-item>
      <el-form-item label="封面">
        <ImageUpload ref="addCategory" :img-url="formData.image" />
      </el-form-item>
    </el-form>
    <el-row slot="footer">
      <el-button size="small" type="primary" @click="btnOK">确定</el-button>
      <el-button size="small" @click="btnCancel">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { addCategory, editCategory } from '@/api/category'
export default {
  props: {
    isShowDialog: {
      type: Boolean,
      default: false
    },
    cateData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      formData: {
        title: '',
        desc: '',
        image: ''
      },
      rules: {
        title: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          { max: 50, message: '最多不能超过50字符', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          { max: 50, message: '最多不能超过50字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    cateData() {
      console.log(123)
      this.formData = this.cateData
    }
  },

  methods: {
    async  btnOK() {
      await this.$refs.addInfo.validate()
      this.formData.image = this.$refs.addCategory.fileList[0].url
      if (this.cateData.id) {
        await editCategory(this.cateData)
        this.$message.success('修改成功')
        this.formData.image = ''
      } else {
        await addCategory(this.formData)
        this.$message.success('添加成功')
      }
      this.$refs.addCategory.fileList.splice(0, 1)
      this.$emit('update:isShowDialog', false)
      this.$emit('reloadPage', this.cateData.id)
    },
    btnCancel() {
      this.formData = {
        title: '',
        desc: '',
        image: ''
      }
      this.$refs.addInfo.resetFields()
      this.$emit('update:isShowDialog', false)
      this.$emit('update:cateData', {})
      this.$refs.addCategory.fileList = []
    }
  }
}
</script>

<style>

</style>
